<?php
header('Content-Type:text/plain;charset=utf-8');
/**
 * 砍价活动
 *
 * Date: 2017/7/17
 * Time: 16:59
 */

defined('InNcPHP') or exit('Access Invalid!');

class bargainControl  extends  BaseHomeControl {

    public $redis;

    public $deploy;

    public  function  __construct()
    {
        $this->redis = new Redis();
        $this->deploy = C('redis');
        $this->redis->connect($this->deploy['master']['host'],$this->deploy['master']['port']);
        parent::__construct();
        Tpl::setLayout('bargain_layout');
        Tpl::setDir('bargain');
    }

    /**
     * 活动列表
     */
    public function indexOp(){
            $bargain_model = Model('bargain');
            $city_id = $_SESSION['pos']['city_id'];
            $time = time();
            if(!empty($_GET['type']) || !empty($_GET['hot'])){
                if($_GET['type']==1){
                    //获取同城实体店商品
                $string = "(type=1 &&firm_city_id =$city_id) and if_show=1 and $time between start_time and end_time";
                $bargain_list = $bargain_model->getBarginlistPage($string,'*',10,' is_hot desc,bg_rs desc');
                $title = '同城商家';

               }
                if($_GET['type']==2){
                    //爆款商品
                 $string = "(type=0 ) and if_show=1  and $time between start_time and end_time";
                 $bargain_list = $bargain_model->getBarginlistPage($string,'*',10,' is_hot desc,bg_rs desc');
                 $title = '旅游特产';
                }
                Tpl::output('bargain_list',$bargain_list);
                //ajax 加载分 页
                if (isset($_GET['isajax']) && $_GET['isajax'] == 1) {
                    Tpl::showpage('bargain_type_list_page', 'null_layout');
                    exit;
                }
                Tpl::output('title',$title);
                Tpl::output('TotalNum',pagecmd("gettotalnum"));
                Tpl::output('TotalPage',pagecmd("gettotalpage"));
                Tpl::showpage('bargain_type_list');
                exit;

            }

           $string = "(type=0 or type=1 &&firm_city_id =$city_id) and if_show=1 and $time between start_time and end_time";
           $bargain_list = $bargain_model->getBarginlistPage($string,'*',10,' is_hot desc,bg_rs desc');
           Tpl::output('bargain_list',$bargain_list);
           //ajax 加载分页
           if (isset($_GET['isajax']) && $_GET['isajax'] == 1) {
            Tpl::showpage('bargain_list_page', 'null_layout');
            exit;
           }
           Tpl::output('TotalNum',pagecmd("gettotalnum"));
           Tpl::output('TotalPage',pagecmd("gettotalpage"));
           Tpl::showpage('bargain_index');

  }

    /**
     * 活动详情
     */
     public  function bargain_infoOp(){
         $bargain_model = Model('bargain');
         $member_order_model = Model('bargain_order');
         $bargain_count_model = Model('bargain_count');
         $member_id = intval($_SESSION['member']['member_id']);
         $bargain_id = intval($_GET['bargain_id']);
         $order_id = intval($_GET['order_id']);

         if(empty($bargain_id)){
             showMessage('参数有误','','html','error');
         }
         $bargain_info = $bargain_model->getBargainInfo(array('bargain_id'=>$bargain_id));
         if(empty($bargain_info)){
             showMessage('参数有误','','html','error');
         }
         //判断该订单属于谁
         if(!empty($order_id)){
             $number = $bargain_count_model->getBgargincount($order_id); //统计帮忙砍价的总人数
             //判断是否是自己订单
             $result1 = $member_order_model->Checkismeorder($order_id,$member_id,$bargain_id);
             $result = $member_order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));
             if($result1){
                 $status = 'myorder';

             }elseif(empty($result)){

                 showMessage('参数有误','','html','error');

             }else{
                 //帮朋友砍价
                 $status = 'helporder';
              }
             //获取帮砍帮前四名;
             $count_civil = $bargain_count_model->getCountPage(array('bg_order_id'=>$order_id),'*',4,'cuont_sunm desc');//获取帮砍价前四名
             $paid_civil  = $bargain_count_model->getCountPage(array('bg_order_id'=>$order_id),'*',4,'paid_sunm desc');//获取代付的前四名
             $result = $member_order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));
             //帮砍前四名用户信息
             Tpl::output('count_civil', $count_civil);//砍价前四
             Tpl::output('paid_civil', $paid_civil);//代付前四
             Tpl::output('order_info',$result);
         }else{
             //查询该用户有没有参加该活动
             $condition = array();
             $condition['member_id'] = $member_id;
             $condition['bargain_id'] = $bargain_id;
             //$condition['bg_order_status'] = array('neq','20');
             $res = $member_order_model->getBgOrderInfo($condition);
             //如果有参加获取砍价以及代付列表
             if(!empty($res)){
                 //获取该订单代付榜单
                 $status = 'myorder';
                 $number = $bargain_count_model->getBgargincount($res['bg_order_id']); //统计帮忙砍价的总人数
                 //获取帮砍帮前四名;
                 $count_civil = $bargain_count_model->getCountPage(array('bg_order_id'=>$res['bg_order_id']),'*',4,'cuont_sunm desc');//获取帮砍价前四名
                 $paid_civil  = $bargain_count_model->getCountPage(array('bg_order_id'=>$res['bg_order_id']),'*',4,'paid_sunm desc');//获取代付的前四名
                 $result = $member_order_model->getBgOrderInfo(array('bg_order_id'=>$res['bg_order_id']));
                 //帮砍前四名用户信息
                 Tpl::output('count_civil', $count_civil);//砍价前四
                 Tpl::output('paid_civil', $paid_civil);//代付前四
                 Tpl::output('order_info',$res);

             }else{
                 //该用户什么都没参加也不是帮别人砍价
                 $status = 'null';

             }
         }

         //微信分享JSsdk
         require_once(BASE_DATA_PATH."/vendors/weixin_share/jssdk.php");
         $model = Model('');
         $link_info = $model->table('bargain_link')->find();
         $jssdk = new JSSDK();
         $signPackage = $jssdk->getSignPackage();
         Tpl::output('link_info',$link_info);
         Tpl::output('signPackage',$signPackage);//微信分享参数
         Tpl::output('number',$number);//帮忙的总人数
         Tpl::output('member',$_SESSION['member']);//用户信息
         Tpl::output('status',$status);//用户与活动的状态
         Tpl::output('bargain_info',$bargain_info);//活动信息
         Tpl::output('is_weixin',$this->is_weixin());//判断是否在微信中
         //var_dump($_SERVER['HTTP_HOST']);
        // var_dump($_SERVER['REQUEST_URI']);
         Tpl::output('get',$_GET);
         Tpl::showpage('info');
     }



    /**
     * 用户点击参加活动
     */


    public function  joinactivityOp(){
           $bargain_model = Model('bargain');
           $bargain_order = Model('bargain_order');
           $bargain_id = intval($_POST['bargain_id']);
           $member_id  = intval($_POST['member_id']);

           //查询该用户是否已经参加了该活动
           $if_join = $bargain_order->getBgOrderInfo(array('bargain_id'=>$bargain_id,'member_id'=>$member_id));
           if(!empty($if_join)){
               output_error(array('code'=>400,'msg'=>'您已经参加过了,请勿重复提交'));
           }
           //查询该活动是否正在进行中
           $bargain = $bargain_model->checkActivity($bargain_id);
           if(!empty($bargain)){
               //查询活动是否需要关注公众号
               if($bargain['if_code']=='1'){
                   //查询用户是否关注了公共号
                   require_once(BASE_DATA_PATH.'/vendors/wechat/wesdk.php');
                   $wesdk = new wesdk();
                   $u = $wesdk->getUserInfo($_SESSION['member']['openid']);
                   //判断是否在微信中
                   if($this->is_weixin()){
                       //未关注就强行关注
                       if($u['subscribe'] !==1){
                           output_error(array('code'=>300,'msg'=>'您还没有关注公众号噢！'));
                       }
                   }

               }
               //判断是否属于爆款活动
               if($bargain['is_hot']=='1'){
                 //判断砍到低价人数是否已满
                 $condition = array();
                 $condition['bargain_id'] = $bargain_id;
                 $condition['min_time']   = array('neq','null');
                 $count = $bargain_order->getBgOrderCount($condition);
                 if($count>$bargain['bg_store']){
                     output_error(array('code'=>200,'msg'=>'很遗憾,活动人数已经满！'));
                 }

               }
           //生成活动订单
           $order_params = array();
           $order_params['bg_order_sn'] =  str_pad($_SESSION['member']['member_id'], 11, strrev(time())) . mt_rand(100000, 999999);
           $order_params['member_id']   = $member_id;
           $order_params['merchant_id'] = $bargain['merchant_id'];
           $order_params['bargain_id']  = $bargain['bargain_id'];
           $order_params['bg_order_price']= $bargain['bg_price'];
           $order_params['bg_order_status']= '10';
           $order_params['bg_price']    = $bargain['bg_price'];
           $order_params['bg_title']    = $bargain['bg_title'];
           $order_params['add_time']    = time();
           $order_params['bg_title']    = $bargain['bg_title'];
           $order_params['type']        = $bargain['type'];
           $order_params['bg_thumb']    = $bargain['bg_thumb'];
           $order_params['bg_floorprice']= $bargain['bg_floorprice'];
           $order_params['nickname']= $_SESSION['member']['nickname'];
           $res = $bargain_order->addBgOrder($order_params);
           //插入成功计算第一次砍价的金额
           if($res){
               $true_price = randomFloat($bargain['min_price'],$bargain['max_price']);
               //订单信息写入redis缓存
               $name = $this->deploy['prefix'].'orders'.$res;
               $order_params['bg_order_price'] = $bargain['bg_price'];
               $this->redis->hSet($name,'member_id',$_SESSION['member']['member_id']);//订单用户ID
               $this->redis->hSet($name,'order_id',$res);
               $this->redis->hSet($name,'bargain_id',$bargain['bargain_id']);//商品ID
               $this->redis->hSet($name,'in_all',0);//砍价总次数
               $this->redis->hSet($name,'bg_order_price',$order_params['bg_order_price']);//订单当前价格
               $this->redis->hSet($name,'bg_floorprice',$order_params['bg_floorprice']);//订单可以砍到的最低价
               $this->redis->hSet($name,'nickname',$_SESSION['member']['nickname']);//用户昵称
               $this->redis->hSet($name,'bg_title',$bargain['bg_title']);//商品名称
               $pxname = $this->deploy['prefix'].'orderpx';
               $this->redis->zAdd($pxname,0,'order_id-'.$res);
               //单个订单本月份的砍价次数
               $monthordername= $this->deploy['prefix'].'month_order'.$res;
               $this->redis->hSet($monthordername,'order_id',$res);
               $this->redis->hSet($monthordername,'in_all',0);//砍价总次数
               $this->redis->hSet($monthordername,'nickname',$_SESSION['member']['nickname']);//用户昵称
               $this->redis->hSet($monthordername,'bg_title',$bargain['bg_title']);//商品名称
               //执行砍价操作
               $bargain_model->addbargainres($bargain_id);
               $bargain_order->updateorder_price($res,$true_price,$member_id,$_SESSION['member']['nickname'],$_SESSION['member']['headimgurl']);




               output_data($true_price);
           }else{
               output_error(array('code'=>200,'msg'=>'系统出错,请重新提交'));
           }

       }else{
               output_error(array('code'=>200,'msg'=>'活动已过期'));
           }



    }


    /**
     * 点击帮忙砍价
     */

    public function help_bargainOp(){



        $bargain_order = Model('bargain_order');
        $order_id  = intval($_POST['order_id']);
        $member_id = intval($_POST['member_id']);
        $bargain_id= intval($_POST['bargain_id']);
        $t = time();
        $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));//当天的结束时间戳
        $d =$this->timediff($t,$end);
        //判断该活动有没有过期
        $name = $this->deploy['prefix'].'bargain_'.$bargain_id;
        $re = json_decode($this->redis->get($name),true);

        if($re['if_show'] == 0 || $re['end_time']< time()){
            output_error(array('code'=>-200,'msg'=>'活动已经过期'));
        }
        //防止用户自己刷砍价
        $result = $this->redis->hGet($this->deploy['prefix'].'orders'.$order_id,'member_id');

        if($result == $member_id){
            output_error(array('code'=>-200,'msg'=>'非法操作'));
        }
        $monthordername= $this->deploy['prefix'].'month_order'.$order_id;
        $isorder = $this->redis->hGetAll($monthordername);
        if(empty($isorder)){
            //缓存中订单为空,说明该条订单是上个月的重新从数据库取出来重新写入写入缓存
            $new_order_info = $bargain_order->getBgOrderInfo(array('bg_order_id'=>$order_id));
            $this->redis->hSet($monthordername,'order_id',$order_id);
            $this->redis->hSet($monthordername,'in_all',0);//砍价总次数
            $this->redis->hSet($monthordername,'nickname',$new_order_info['nickname']);//用户昵称
            $this->redis->hSet($monthordername,'bg_title',$new_order_info['bg_title']);//商品名称

        }

        //判断用户是不是第一次对此单进行砍价
        //$bargain_count_model = Model('bargain_count');
        $order_sum_name = $this->deploy['prefix'].'orderu-'.$order_id.'-'.$member_id;
        $friend_name = $this->deploy['prefix'].'fried_order'.$order_id.'-'.$member_id;
        $res = $this->redis->hGetAll($order_sum_name);
        //$res  = $bargain_count_model->checkOnebargain($member_id,$order_id);
        if(empty($res)){
            $this->redis->set($friend_name,'1',$d);
            $true_price = randomFloat($re['min_price'],$re['max_price']);
            $true_price_1=$bargain_order->updateorder_price($order_id,$true_price,$member_id,$_SESSION['member']['nickname'],$_SESSION['member']['headimgurl']);
            output_data($true_price_1);

        }else{
            $friend = $this->redis->get($friend_name);
            if($friend){
                if($friend<$re['true_sum']){
                    $this->redis->incrBy($friend_name,1);
                    //计算第二次砍价成功的概率和金额
                    $bg_degree = $re['bg_degree'];//第二次砍价成功的次数范围
                    //$result = $bargain_count_model->getbargain_countInfo(array('member_id'=>$member_id,'bg_order_id'=>$order_id));//用户砍价总次数
                    $result = $this->redis->hGetAll($order_sum_name);//取缓存中用户砍价总次数
                    $total = $result['in_all'];
                    $true_sum = $result['true_all'];//砍成功总次数
                    $now = $true_sum - ceil($total/$bg_degree);
                    if($now <= 0){
                        $times = $bg_degree - $total % $bg_degree;
                        if(mt_rand(1,$times) == 1){
                            //中奖
                            $true_price = randomFloat($re['min_price'],$re['max_price']);//计算砍中价格
                            $true_price_1 = $bargain_order->updateorder_price($order_id,$true_price,$member_id);
                            output_data($true_price_1);
                        }else {
                            $bargain_order->updateorder_price($order_id,null,$member_id);
                            output_error(array('code'=>-100,'msg'=>'砍价失败'));
                        }
                    } else {
                        $bargain_order->updateorder_price($order_id,null,$member_id);
                        output_error(array('code'=>-100,'msg'=>'砍价失败'));

                    }
                }else{
                    output_error(array('code'=>-200,'msg'=>'您今天已经给力了,请明天再来帮砍噢！'));
                }

            }else{
                $this->redis->set($friend_name,'1',$d);
                //计算第二次砍价成功的概率和金额
                $bg_degree = $re['bg_degree'];//第二次砍价成功的次数范围
                //$result = $bargain_count_model->getbargain_countInfo(array('member_id'=>$member_id,'bg_order_id'=>$order_id));//用户砍价总次数
                $result = $this->redis->hGetAll($order_sum_name);//取缓存中用户砍价总次数
                $total = $result['in_all'];
                $true_sum = $result['true_all'];//砍成功总次数
                $now = $true_sum - ceil($total/$bg_degree);
                if($now <= 0){
                    $times = $bg_degree - $total % $bg_degree;
                    if(mt_rand(1,$times) == 1){
                        //中奖
                        $true_price = randomFloat($re['min_price'],$re['max_price']);//计算砍中价格
                        $true_price_1 = $bargain_order->updateorder_price($order_id,$true_price,$member_id);
                        output_data($true_price_1);
                    }else {
                        $bargain_order->updateorder_price($order_id,null,$member_id);
                        output_error(array('code'=>-100,'msg'=>'砍价失败'));


                    }
                } else {
                    $bargain_order->updateorder_price($order_id,null,$member_id);
                    output_error(array('code'=>-100,'msg'=>'砍价失败'));

                }
            }


       }
  }

  /**
   * 增加分享次数
   */

    public  function add_shareOp(){

        $model = Model('bargain');
        $bargain_id = intval($_GET['bargain_id']);
        $model->add_share_sun($bargain_id);
     }

    public  function testfromOp(){
        Tpl::showpage('testform');
    }

    /**
     * 获取当天还剩多少秒
     * @param $begin_time
     * @param $end_time
     * @return int
     */
    function timediff($begin_time,$end_time){
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }

        //计算天数
        $timediff = $endtime-$starttime;
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        //$res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        $s= ($hours*3600)+($mins*60)+$secs;
        return $s;
    }



}